#!/usr/bin/env python
# -*- coding:utf-8 -*-
import gtk
gtk.gdk.threads_init()

import vlc

import threading
import time

class AudioPlayer(gtk.VBox):
	"""Player Widget, fonctionnality:
		play
		pause
		stop
		next
		previous
		download
		switch position(hscal bar)
	"""
	def __init__(self,player):
		gtk.VBox.__init__(self)

		#Ajustement
		self.adjust = gtk.Adjustment(value=0, lower=0, upper=10, step_incr=1000, page_incr=1000, page_size=0)
		
		#Barre deplacement
		self.gradateurh = gtk.HScale(self.adjust)
		self.gradateurh.set_draw_value(False)
		self.gradateurh.connect("change_value",self.onValueChanged)
		self.pack_start(self.gradateurh,expand=False)
		
		#Label affichant le temps
		self.label_temps = gtk.Label('--:--/--:--')
		self.pack_start(self.label_temps)
		
		#Barre d'outil
		self.barre_outil = gtk.Toolbar()
		self.barre_outil.set_style(gtk.TOOLBAR_ICONS)
		prevb = gtk.ToolButton(gtk.STOCK_MEDIA_PREVIOUS)
		self.barre_outil.insert(prevb,0)
		playb = gtk.ToolButton(gtk.STOCK_MEDIA_PLAY)
		self.barre_outil.insert(playb,1)
		pauseb = gtk.ToolButton(gtk.STOCK_MEDIA_PAUSE)
		self.barre_outil.insert(pauseb,2)
		nextb = gtk.ToolButton(gtk.STOCK_MEDIA_NEXT)
		self.barre_outil.insert(nextb,3)
		stopb = gtk.ToolButton(gtk.STOCK_MEDIA_STOP)
		self.barre_outil.insert(stopb,4)
		separator1 = gtk.SeparatorToolItem()
		self.barre_outil.insert(separator1,5)
		downloadb = gtk.ToolButton(gtk.STOCK_GO_DOWN)
		self.barre_outil.insert(downloadb,6)

		#Signals
		playb.connect("clicked",self.onPlay)
		pauseb.connect("clicked",self.onPause)
		prevb.connect("clicked",self.onPrev)

		self.add(self.barre_outil)

		self.show_all()

		#player is a parameter of the class
		self.toolplayer = player

		#Boolean
		self.exit = False
		#Thread for scale
		self.thread = threading.Thread(target=self.defilScale_thread)

	def initThread(self):
		self.thread = threading.Thread(target=self.defilScale_thread)

	def onPlay(self,event):
		"""Play file"""
		self.toolplayer.play()

	def onPause(self,event):
		"""Pause file"""
		self.toolplayer.pause()
	
	def onPrev(self,event):
		"""Previous file"""
		self.toolplayer.set_position(0)

	def onValueChanged(self,event,user,value):
		print 'Jump to '+str(self.getinms(int(value)))
		self.toolplayer.set_time(int(value))

	#convert long int to string format time(minute:seconds)
	def getinms(self,time):
		tmp_second = time / 1000
		
		return '%02d:%02d' % (tmp_second/60,tmp_second%60)

	def defilScale_thread(self):
		while not self.exit:
			time.sleep(0.5)
			if self.toolplayer.is_playing:
				self.label_temps.set_text(self.getinms(int(self.toolplayer.get_time()))+
										  '/'+
										  self.getinms(int(self.toolplayer.get_length())))
				self.adjust.set_upper(int(self.toolplayer.get_length()))
				self.adjust.set_value(int(self.toolplayer.get_time()))
